"use client"
import { useOptimistic } from "react";
import Link from "next/link";
import { removeProduct } from "@/actions/products";

export type Product = {
    id: number,
    title: string,
    price: number,
    description: string | null
}

export default function ProductsDeletePage({ products }: { products: Product[] }) {
    const [optimisticProducts, setOptimisticProducts] = useOptimistic(products, (currentProducts, productId) => {
        return currentProducts.filter(product => product.id !== productId);
    });
    const removeProductById = async (productId: number) => {
        setOptimisticProducts(productId);
        await removeProduct(productId);
    };
    return (
        <div>
            <h1 className="text-3xl text-center font-bold">Products DB Page</h1>
            <ul className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
                {
                    optimisticProducts.map(product => (
                        <li
                            key={product.id}
                            className="p-4 shadow-md rounded-lg text-gray-700 bg-amber-50 hover:bg-amber-100 transition-all cursor-pointer"
                        >
                            <Link href={`/products-db/${product.id}`}>
                                <h2 className="text-2xl font-semibold">{product.title}</h2>
                            </Link>
                            <p>{product.description}</p>
                            <p className="text-lg font-medium">￥{product.price}</p>
                            <form action={removeProductById.bind(null, product.id)}>
                                <button
                                    type="submit"
                                    className="px-4 py-2 text-white bg-red-500 rounded-md hover:bg-red-700"
                                >
                                    Delete
                                </button>
                            </form>
                        </li>
                    ))
                }
            </ul>
        </div>
    )
}
